layui.use(['form', 'upload', 'backend', 'eleTree'],function(){
    var form = layui.form;
    var $ = layui.jquery;
    var upload = layui.upload;
    var backend = layui.backend;
    var eleTree = layui.eleTree;

    var eleTreeConfig = {
        el: '#form-role',
        url: '/admin/admin/role',
        where : {
            id : $("#form-role").data('id')
        },
        showCheckbox: true,
        response: {   // 对于后台数据重新定义名字
            statusName: "code",
            statusCode: 1,
            dataName: "data"
        },
        checkStrictly : true,
        isDefaultChangePstatus:true,
        checkOnClickNode: true,
        request: {     // 对后台返回的数据格式重新定义
            name: "nickname",
            key: "id",
            children: "childlist",
            checked: "checked",
            disabled: "disabled",
            isLeaf: "isLeaf"
        },
    };

    var eleTreeObj = eleTree(eleTreeConfig);

    //头像上传
    var uploadInst = upload.render({
        elem: '.upload'
        ,url: '/admin/attachment/upload' //改成您自己的上传接口
        ,done: function(res){
            //如果上传失败
            if(res.code != 1){
                return layer.msg('上传失败:' . res.msg);
            }
            $("#c-avatar").val(res.data.path).trigger('change');
        }
    });

    $("#c-avatar").change(function() {
        $('.img-preview').attr('src', $(this).val());
    });

    $(".attachment").click(function () {
        backend.api.open('/admin/attachment/select', '选择', {
            callback : function (data) {
                $("#c-avatar").val(data[0]['url']).trigger('change');
            }
        });
    });

    form.on('submit(save)', function(data){
        var eleTreeSelect = eleTreeObj.getChecked(false, true);
        var roleIds = [];
        layui.each(eleTreeSelect, function (k,v) {
            roleIds.push(v.id);
        });
        data.field['form[roleids]'] = roleIds;
        var loading = layer.load();
        $.ajax({
            url: data.form.action,
            data: data.field,
            type:'post',
            success:function(res){
                if(res.code == 1){
                    layer.msg(res.msg,{icon:1,time:1000},function(){
                        backend.api.close()
                    });
                }else{
                    layer.confirm(res.msg, {icon: 3, title:'警告'}, function(index){
                        layer.close(index);
                    });
                }
            },
            complete : function () {
                layer.close(loading);
            }
        });
        return false;
    });
});
